﻿using FPSO.HMI.Utils;
using FPSO.Models.ViewModel.Controls;
using MySql.Data.MySqlClient;
using Opc.Ua;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Security.Cryptography;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;

namespace FPSO.HMI.Controls
{
    /// <summary>
    /// UCAlarmList.xaml 的交互逻辑
    /// </summary>
    public partial class UCAlarmStatusList : UserControl
    {

        private UCAlarmListViewModel viewModel;
        private DispatcherTimer refreshTimer; // 添加定时器

		//通过m_PageName作为显示内容的筛选
		private string m_PageName;
        public UCAlarmStatusList()
        {
            InitializeComponent();

            viewModel = new UCAlarmListViewModel();
            this.DataContext = viewModel;
			m_PageName = Convert.ToString(this.Name);

            if(LoadData() == true)
			{
				// 初始化定时器
				refreshTimer = new DispatcherTimer();
				refreshTimer.Interval = TimeSpan.FromSeconds(3); // 设置3秒间隔
				refreshTimer.Tick += RefreshTimer_Tick;
				refreshTimer.Start(); // 启动定时器
			}
		}

        /// <summary>
        /// 加载报警数据
        /// </summary>
        private bool LoadData()
        {
            try
            {
                string connectionString = ConfigurationManager.AppSettings["MySQLStr"];

                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();

                    string sqlQuery = "SELECT log_id, log_createtime, log_updatetime,log_name, log_type, log_state FROM systemlog ORDER BY log_createtime DESC";

                    using (MySqlCommand cmd = new MySqlCommand(sqlQuery, connection))
                    {
						using (MySqlDataAdapter adapter = new MySqlDataAdapter(cmd))
                        {
                            DataTable dataTable = new DataTable();
                            adapter.Fill(dataTable);
                            List<AlarmInfo> alarmList = new List<AlarmInfo>();
                            foreach (DataRow row in dataTable.Rows)
                            {
								int type = Convert.ToInt32(row["log_type"]);
								if(type == 6)
								{
									alarmList.Add(new AlarmInfo
									{
										LogId = Convert.ToInt32(row["log_id"]),
										LogCreateTime = Convert.ToDateTime(row["log_createtime"]),
										LogName = row["log_name"].ToString(),
										LogType = Convert.ToInt32(row["log_type"]),
										LogState = Convert.ToInt32(row["log_state"]),
										LogUpdateTime = Convert.ToDateTime(row["log_updatetime"])
									});
								}
							}
							viewModel.AlarmList = alarmList;
							return true;
						}
					}
                }
            }
            catch (Exception ex)
            {
				CommUtil.AddSystemLog(7, 11, ex.Message);
				return false;
            }
        }

        /// <summary>
        /// 定时刷新事件处理程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshTimer_Tick(object sender, EventArgs e)
        {
            if(LoadData()== false) // 在每隔3秒刷新数据
			{
				refreshTimer.Stop();
			}
        }

        /// <summary>
        /// 状态切换按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StateChangeButton_Click(object sender, RoutedEventArgs e)
        {
            // 获取当前行的数据
            Button button = (Button)sender;
            AlarmInfo alarmInfo = button.DataContext as AlarmInfo;
            // 放行未处理数据
            if (alarmInfo != null && alarmInfo.LogState == 0)
            {
                // 切换状态为已处理
                alarmInfo.LogState = 1;
                // 提交数据库
                UpdateLogStateInDatabase(alarmInfo);
                // 刷新数据
                LoadData();
            }
        }


        /// <summary>
        /// 更新数据库中的LogState值
        /// </summary>
        /// <param name="alarmInfo"></param>
        private void UpdateLogStateInDatabase(AlarmInfo alarmInfo)
        {
            try
            {
                string connectionString = ConfigurationManager.AppSettings["MySQLStr"];

                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();

                    string sqlQuery = "UPDATE systemlog SET log_state = @LogState, log_updatetime = @LogUpdateTime WHERE log_id = @LogId";

                    using (MySqlCommand cmd = new MySqlCommand(sqlQuery, connection))
                    {
                        cmd.Parameters.AddWithValue("@LogState", alarmInfo.LogState);
                        cmd.Parameters.AddWithValue("@LogId", alarmInfo.LogId);
                        cmd.Parameters.AddWithValue("@LogUpdateTime", DateTime.Now);
						cmd.ExecuteNonQuery();
                    }
                    LoadData();
                }
            }
            catch (Exception ex)
            {
				CommUtil.AddSystemLog(7, 13, ex.Message);
            }
        }
    }
}
